package com.anxin.registerManagement.service;

import com.anxin.registerManagement.bean.dto.FinanceSearchJo;
import com.anxin.registerManagement.bean.persist.Finance;
import com.anxin.registerManagement.bean.persist.User;
import com.anxin.registerManagement.mapper.FinanceMapper;
import com.anxin.registerManagement.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author anxin
 * @date 2022/4/10 11:13
 */
@Service
public class FinanceService {

    @Autowired
    FinanceMapper financeMapper;

    @Autowired
    UserMapper userMapper;

    public PageInfo<Finance> search(FinanceSearchJo financeSearchJo) {
        LambdaQueryWrapper<Finance> financeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!ObjectUtils.isEmpty(financeSearchJo.getPageNum()) && !ObjectUtils.isEmpty((financeSearchJo.getPageSize()))) {
            PageHelper.startPage(financeSearchJo.getPageNum(), financeSearchJo.getPageSize());
        }
        if (!ObjectUtils.isEmpty(financeSearchJo.getNickName())) {
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.select(User::getId)
                    .like(User::getNickName, financeSearchJo.getNickName());
            List<Integer> userIdList = userMapper.selectObjs(userLambdaQueryWrapper).stream().map(o -> (Integer) o).collect(Collectors.toList());
            // TODO:这里应该写到mapper里，懒得写了
            if (userIdList.size() > 0) {
                financeLambdaQueryWrapper.in(Finance::getUserId, userIdList);
            }
        }
        return new PageInfo<>(financeMapper.selectList(financeLambdaQueryWrapper));
    }

    public void add(Finance finance) {
        // TODO:这里userid唯一
        financeMapper.insert(finance);
    }

    public void update(Finance finance) {
        // TODO:这里userid唯一
        financeMapper.updateById(finance);
    }

    public void delete(List<Integer> id) {
        // TODO:这里需要与用户关联删除
        financeMapper.deleteBatchIds(id);
    }

}
